<?php
namespace app\store\model;

use app\common\model\BaseModel;
use app\common\model\User as UserModel;
use app\common\model\user\Grade;
use app\store\model\store\Dermember;

class ApplyGrade extends BaseModel{
    protected $autoWriteTimestamp = true;

    private $searchNickName = '';
    private $searchMobile = '';
    // 关联会员级别
    public function grade(){
        return $this->hasOne(Grade::class,'grade_id','grade_id')
            ->bind(['grade_name'=>'name']);
    }
    // 关联用户表数据
    public function user()
    {
        return $this->hasOne(UserModel::class, 'user_id', 'user_id')
            ->with(['avatar'])
            ->bind([
                'nick_name',
                'expend_money' => 'pay_money',
                'avatar_url',
                'platform',
                'mobile'
            ]);

    }
    // 关联经销商数据
    public function dermerber(){
        return $this->hasOne(Dermember::class,'user_id','user_id')
            ->bind(['pcount']);
    }

    // 获取待申请经销商数据
    public function getAppleList(array $param = []){
        // 检索查询条件
        $filter = $this->getFilter($param);
        if($this->searchNickName == '' && $this->searchMobile == ''){
            return $this->with(['user','dermerber','grade'])
                ->where($filter)
                ->where(['status'=>0])
                ->paginate(15);
        }else{
            return $this
                ->withJoin('user','left')
                ->with(['dermerber','grade'])
                ->whereRaw("(from_base64(user.nick_name) like '%{$this->searchNickName}%') or (user.mobile = '{$this->searchMobile}')")
                ->where(['status'=>0])
                ->paginate(15);
        }
    }

    /**
     * 获取查询条件
     * @param array $param
     * @return array
     */
    private function getFilter(array $param = [])
    {
        // 默认查询条件
        $params = $this->setQueryDefaultValue($param, [
            'search' => '',     // 微信昵称
            'gender' => -1,     // 用户性别
            'grade_id' => 0,       // 用户等级
        ]);
        // 检索查询条件
        $filter = [];
//        $filter['search'] = [];
        // 微信昵称
        if(!empty($params['search']) ){
            if(is_numeric($params['search'])){
                $this->searchMobile = $params['search'];
            }else{
                $this->searchNickName = $params['search'];
            }
        }

        // 用户性别
        $params['gender'] > -1 && $filter[] = ['gender', '=', (int)$params['gender']];
        // 用户等级
        $params['grade_id'] > 0 && $filter[] = ['grade_id', '=', (int)$params['grade_id']];
        // 起止时间
        if (!empty($params['betweenTime'])) {
            $times = between_time($params['betweenTime']);
            $filter[] = ['create_time', '>=', $times['start_time']];
            $filter[] = ['create_time', '<', $times['end_time'] + 86400];
        }
        return $filter;
    }

    // 添加申请记录
    public static function add(int $store_id,int $user_id,int $grade_id):bool
    {
        $r = self::where(['user_id'=>$user_id,'grade_id'=>$grade_id])->findOrEmpty();
        if($r->isEmpty()){
            $idKey = $r->insert([
                'store_id' => $store_id,
                'user_id' => $user_id,
                'grade_id' => $grade_id
            ]);
            return $idKey>0;
        }else{
            throwError('请勿重复申请!',500);
        }
        return false;
    }

    // 设置审核通过时状态
    public static function setStatus(int $user_id,int $status = 1):bool
    {
        return self::where(['user_id'=>$user_id,'store_id'=>getStoreId()])
            ->save(['status'=>$status]);
    }
}
